package org.sun.web.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.sun.basic.dao.IGroupDao;
import org.sun.basic.dao.ISourceDao;
import org.sun.basic.dao.IUserDao;
import org.sun.basic.model.Group;
import org.sun.basic.model.Source;

public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	private final Logger logger=LoggerFactory.getLogger(getClass());
	
	@Inject
	private ISourceDao sourceDao;
	
	@Inject
	private IGroupDao groupDao;
	
	@Inject
	private IUserDao userDao;
	
	private static Map<String ,Collection<ConfigAttribute>> resourceMap=null;
	
	public MySecurityMetadataSource() {
		
	}

	private void loadResourceDefine() {
		// 提取系统中的所有权限。
		List<Group> grps=groupDao.list("from Group");
		if(resourceMap==null)
		      resourceMap=new HashMap<String ,Collection<ConfigAttribute>>();
		for(Group grp:grps){
			ConfigAttribute cfg=new SecurityConfig(grp.getGrpcode());
			String hql="from Source where id in(select sourceId from GrpSrcSel where groupId=?)";
			List<Source> srcs=sourceDao.list(hql, grp.getId());
			for(Source src:srcs){
				String url=src.getSrcuri();
				if(resourceMap.containsKey(url)){
					Collection<ConfigAttribute> values=resourceMap.get(url);
					values.add(cfg);
					resourceMap.put(url, values);
				}else{
					Collection<ConfigAttribute> values=new ArrayList<ConfigAttribute>();
					values.add(cfg);
					resourceMap.put(url, values);
				}
			}
		}
		
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		if(resourceMap==null)loadResourceDefine();
		//object getRequestUrl 是获取用户请求的url地址
		String url=((FilterInvocation)object).getRequestUrl();
		//产看权限MAP里面是否包含了请求URL的权限集，如果有返回对应的权限集，
		Collection<ConfigAttribute>resultAuth=resourceMap.get(url);
		if(resultAuth!=null)return resultAuth;
		//如果为null返回null表示没有找到对应URL的权限集，不再调用MyAccessDecisionManager类里的decide方法进行权限验证，代表允许访问页面
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}

}
